package itsm.isperp.framework.web.converter;

import itsm.isperp.framework.utils.DateUtils;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;

/**
 * 日期转换器，在系统中对日期型的字段进行转换
 * 
 * @author lizx
 * @date 2013-3-3
 * @version V1.0
 */
public class DateTypeConverter implements Converter<String, Date> {

	public static final Logger logger = LoggerFactory
			.getLogger(DateTypeConverter.class);

	@Override
	public Date convert(String source) {

		source = source.trim();
		if (StringUtils.isEmpty(source)) {
			return null;
		}
		try {
			if (source.length() <= DateUtils.SHORT_DATE) {
				return DateUtils.parseDate(source);
			} else {
				return new java.sql.Timestamp(DateUtils.parseDateTime(source)
						.getTime());
			}
		} catch (ParseException ex) {
			IllegalArgumentException iae = new IllegalArgumentException(
					"Could not parse date: " + ex.getMessage());
			iae.initCause(ex);
			logger.error(ex.getMessage(), ex);
			throw iae;
		}
	}
}
